import { createRouter, createWebHashHistory } from 'vue-router'
import store from "@/store";
const Layout = () => import("@/views/Layout");
const Home = () => import("@/views/home");
const TopCategory = () => import("@/views/category/index.vue");
const Subcategory = () => import("@/views/category/Sub.vue");
const Goods = () => import("@/views/goods/index.vue");
const Login = () => import("@/views/login/index.vue");
const Cart = () => import("@/views/cart/index.vue");
const PayCheckout = () => import("@/views/member/pay/Checkout.vue");
const Pay = () => import("@/views/member/pay/index.vue");
const MemberLayout = () => import("@/views/member/Layout");
const MemberHome = () => import("@/views/member/home");
const MemberOrder = () => import("@/views/member/order");
const routes = [
  {
    path: "/",
    component: Layout,
    children: [
      { path: "/", component: Home },
      { path: "/category/:id", component: TopCategory },
      { path: "/category/sub/:id", component: Subcategory },
      { path: "/product/:id", component: Goods },
      { path: "/cart", component: Cart },
      { path: "/member/checkout", component: PayCheckout },
      { path: "/member/pay", component: Pay },
      {
        path: "/member",
        component: MemberLayout,
        children: [
          { path: "/member", component: MemberHome },
          { path: "/member/order", component: MemberOrder },
        ],
      },
    ],
  },
  {
    path: "/login",
    component: Login,
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  //每次切换路由的时候滚动到顶部
  scrollBehavior() {
    return { left: 0, top: 0 };
  },
});

// 路由拦截
router.beforeEach((to, from, next) => {
  // 用户信息
  const { profile } = store.state.user
  if (!profile.token && to.path.startsWith('/member')) {
    next({ path: "/login", query: { redirectUrl: to.fullPath } }); //next("/login?redirectUrl"+to.fullPath)
  }
  next()
  
})

export default router
